import {
  login,
  logout,
  getUserInfo,
  getMessage,
  getContentByMsgId,
  hasRead,
  removeReaded,
  restoreTrash,
  getUnreadCount
} from '@/api/user'
import {
  setToken,
  TOKEN_KEY,
  clearToken,
  getToken,
  localSave,
  localRead,
  getRoles,
  getVuxRouter,
  setTagNavListInLocalstorage
} from '@/libs/util'

import { mapFun } from '@/libs/tools'
import { loadMenu } from '@/libs/router-util'// 路由

import routes from '../../router/routers.js'
import { endRouter } from '../../router/routers.js'// 404页面

export default {
  state: {
    userName: '',
    userId: '',
    avatarImgPath: '',
    keyToken: getToken(),
    access: '',
    hasGetInfo: false,
    unreadCount: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {},
    login_res_nav: [], // 登录返回来的navlist
    roles: getRoles(), // 登录返回来的角色权限
    login_main_url: '', // 登录成功后，接口返回跳转的页面
    vux_router: getVuxRouter()// 路由
  },
  mutations: {
    setVuxRouter(state, arr) {
     state.vux_router = arr
     let list = arr
     let filterData = []
     // 由于缓存的时候JSON.stringify不能处理函数，过滤掉component，重新生成一个数组

     filterData = list.map(function(cv) {
       // 路由名字
       let name = cv.path.substring(1, cv.path.length)
       let obj = {

         title: cv.title,
         path: cv.path,
         name: name, // cv.name
         icon: cv.icon,
         meta: cv.meta
       }
       if (cv.children) {
          let child = cv.children.map(item => {
           let name = item.path.substring(1, item.path.length)
           return {
             title: item.title,
             path: item.path,
             name: name, // cv.name
             icon: item.icon,
             meta: item.meta
           }
         })
         obj['children'] = child
       }
       return obj
     })
      localSave('vux_router', filterData)
    },
    setMainUrl(state, url) {
      state.login_main_url = url
      localSave('login_main_url', url)
    },
    setNavList(state, navList) {
      state.login_res_nav = navList

      localSave('login_res_nav', navList)
    },
    setRoles(state, roles) {
      state.roles = roles

      localSave('roles', roles)
    },
    setAvatar(state, avatarPath) {
      state.avatarImgPath = avatarPath
    },
    setUserId(state, id) {
      state.userId = id
    },
    setUserName(state, name) {
      state.userName = name
    },
    setAccess(state, access) {
      state.access = access
    },
    setToken(state, token) {
      state.keyToken = token
      setToken(token)
    },
    clearToken(state, token) {
      state.keyToken = ''
      clearToken()
    },
    setHasGetInfo(state, status) {
      state.hasGetInfo = status
    },
    setMessageCount(state, count) {
      state.unreadCount = count
    },
    setMessageUnreadList(state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList(state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList(state, list) {
      state.messageTrashList = list
    },
    updateMessageContentStore(state, {
      msg_id,
      content
    }) {
      state.messageContentStore[msg_id] = content
    },
    moveMsg(state, {
      from,
      to,
      msg_id
    }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    }
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    // 登录
    handleLogin({
      commit
    }, {
      username,
      pwd
    }) {
      username = username.trim()
      return new Promise((resolve, reject) => {
        login({
          username,
          pwd
        }).then(res => {
          console.log(res)
          const data = res.data.data
          // commit('setMainUrl', data.mainUrl);//跳转地址
          commit('setToken', data.token) // token
          // 缓存navList
          commit('setNavList', data.navList)
          // 缓存角色权限
          commit('setRoles', mapFun(data.rules, 'rule'))
          let arr = []
          arr = [...routes, ...loadMenu(), ...endRouter]
          // arr=routes.concat(loadMenu())
          commit('setVuxRouter', arr)
          resolve(data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut({
      state,
      commit
    }) {
      return new Promise((resolve, reject) => {
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口

        commit('clearToken', '')
        commit('setToken', '') // token

        commit('setAccess', [])
        commit('setNavList', [])
        commit('setRoles', [])
        commit('setMainUrl', '')// 跳转地址
        commit('setVuxRouter', [])
        setTagNavListInLocalstorage([])
        resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo({
      state,
      commit
    }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo(state.token).then(res => {
            const data = res.data
            commit('setAvatar', data.avatar)
            commit('setUserName', data.name)
            commit('setUserId', data.user_id)
            commit('setAccess', data.access)
            commit('setHasGetInfo', true)
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    }

  }
}
